// 封装通用的请求方法
// const BASE_URL = 'http://localhost:8899' // 替换为您的实际API地址
const BASE_URL = 'https://www.stellargang.cn' // 替换为您的实际API地址
const TIMEOUT = 10000 // 请求超时时间

// 请求拦截器 - 添加通用headers和token
const addRequestInterceptor = (options) => {
  // 获取存储的token
  const token = uni.getStorageSync('token')
  
  // 设置默认headers
  const defaultHeaders = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
  
  // 如果有token，添加到headers
  if (token) {
    defaultHeaders['Authorization'] = `Bearer ${token}`
  }
  
  // 合并headers
  options.header = {
    ...defaultHeaders,
    ...options.header
  }
  
  return options
}

// 响应拦截器 - 统一处理响应
const handleResponse = (response, resolve, reject) => {
  const { code, data } = response
    // 业务状态码检查
    if (data.code === 200 || data.success) {
      resolve(data)
    } else {
     
      // 业务错误处理
      const errorMsg = data.message || data.msg || '请求失败'
      if (data.code === 400 || data.code === 401) {
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
      }
      // 特殊错误码处理
      if (data.code === 404 || data.code === 403) {
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          // token过期或无权限，跳转到登录页
          uni.removeStorageSync('token')
          uni.removeStorageSync('userInfo')
          uni.navigateTo({
            url: '/pages/login/index'
          })
        }, 2000)
        return
      }      
      reject({
        code: data.code,
        message: errorMsg,
        data: data.data
      })
    }
}

// 通用请求方法
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 显示加载提示
    if (options.showLoading !== false) {
      uni.showLoading({
        title: options.loadingText || '加载中...',
        mask: true
      })
    }
    
    // 处理URL
    const url = options.url.startsWith('http') ? options.url : BASE_URL + options.url
    
    // 添加请求拦截器
    const requestOptions = addRequestInterceptor({
      url,
      method: options.method || 'GET',
      data: options.data || {},
      header: options.header || {},
      timeout: options.timeout || TIMEOUT,
      dataType: options.dataType || 'json',
      responseType: options.responseType || 'text'
    })
    
    // 发起请求
    uni.request({
      ...requestOptions,
      success: (response) => {
        handleResponse(response, resolve, reject)
      },
      fail: (error) => {
        console.error('请求失败:', error)
        
        let errorMsg = '网络连接失败'
        if (error.errMsg) {
          if (error.errMsg.includes('timeout')) {
            errorMsg = '请求超时，请检查网络'
          } else if (error.errMsg.includes('fail')) {
            errorMsg = '网络连接失败，请检查网络'
          }
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
        
        reject({
          code: -1,
          message: errorMsg,
          data: error
        })
      },
      complete: () => {
        // 隐藏加载提示
        if (options.showLoading !== false) {
          uni.hideLoading()
        }
      }
    })
  })
}

// GET请求
const get = (url, params = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data: params,
    ...options
  })
}

// POST请求
const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

// PUT请求
const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

// DELETE请求
const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}

// 文件上传
const upload = (url, filePath, formData = {}, options = {}) => {
  return new Promise((resolve, reject) => {
    // 显示上传进度
    if (options.showLoading !== false) {
      uni.showLoading({
        title: options.loadingText || '上传中...',
        mask: true
      })
    }
    
    // 获取token
    const token = uni.getStorageSync('token')
    const header = {
      ...options.header
    }
    
    if (token) {
      header['Authorization'] = `Bearer ${token}`
    }
    
    uni.uploadFile({
      url: url.startsWith('http') ? url : BASE_URL + url,
      filePath,
      name: options.name || 'file',
      formData,
      header,
      success: (response) => {
        try {
          const data = JSON.parse(response.data)
          if (data.code === 200 || data.success) {
            resolve(data)
          } else {
            const errorMsg = data.message || data.msg || '上传失败'
            uni.showToast({
              title: errorMsg,
              icon: 'none'
            })
            reject({
              code: data.code,
              message: errorMsg,
              data: data.data
            })
          }
        } catch (error) {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject({
            code: -1,
            message: '上传失败',
            data: error
          })
        }
      },
      fail: (error) => {
        console.error('上传失败:', error)
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
        reject({
          code: -1,
          message: '上传失败',
          data: error
        })
      },
      complete: () => {
        if (options.showLoading !== false) {
          uni.hideLoading()
        }
      }
    })
  })
}

// 导出API方法
export default {
  request,
  get,
  post,
  put,
  delete: del,
  upload,
  BASE_URL
}

// 也可以单独导出各个方法
export {
  request,
  get,
  post,
  put,
  del as delete,
  upload,
  BASE_URL
}